//
//  WBEmoticonCell.swift
//  0829-Weibo
//
//  Created by 毕仲阳 on 16/9/9.
//  Copyright © 2016年 mycompany. All rights reserved.
//

import UIKit

class WBEmoticonCell: UICollectionViewCell {
    
    
    var emoticonButtons = [WBEmoticonButton]()
    
    var emoticons:[WBEmoticon]?{
        didSet{
            for button in emoticonButtons {
                button.isHidden = true
            }
            
            for (index,emoticon) in emoticons!.enumerated() {
                let button = emoticonButtons[index]
                button.isHidden = false
                button.emoticon = emoticon
            }
        }
    }
    
    
    var indexPath:IndexPath?{
        didSet{
            label.text = "第\(indexPath!.section)组,第\(indexPath!.item)行"
            recentLabel.isHidden = indexPath?.section != 0
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUI()
    {
        contentView.addSubview(label)
        contentView.addSubview(recentLabel)
        contentView.addSubview(deleteButton)
        label.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(contentView)
        }
        
        recentLabel.snp_makeConstraints { (make)->Void in
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView.snp_bottom).offset(-10)
        }
        self.addChildButtons()
        let ges = UILongPressGestureRecognizer(target: self, action: #selector(longPress(ges:)))
        self.addGestureRecognizer(ges)
    }
    
    @objc private func longPress(ges:UILongPressGestureRecognizer){
        //print(ges.location(in: self))
        func getButton(location:CGPoint)->WBEmoticonButton?{
            for button in emoticonButtons{
                if button.frame.contains(location) {
                    return button
                }
            }
            return nil
        }
        
        switch ges.state {
        case .began,.changed:
            let location = ges.location(in: self)
            if let button = getButton(location: location), button.isHidden == false{
                let emoticon = button.emoticon
                paopaoView.emoticonButton.emoticon = emoticon
                let window = UIApplication.shared.windows.last!
                
                let rect = button.convert(button.bounds, to: window)
                paopaoView.center.x = rect.midX
                paopaoView.frame.origin.y = rect.maxY - paopaoView.frame.height
                window.addSubview(paopaoView)
            }else
            {
                paopaoView.removeFromSuperview()
            }
        case .ended,.cancelled,.failed:
            paopaoView.removeFromSuperview()
        default:
            break
        }
    }
    
    ///MARK: -监听按钮点击事件
    @objc private func emoticonButtonClick(button:WBEmoticonButton){
        //print(button.emoticon?.chs)
        let emoticon = button.emoticon!
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBEmoticonButtonDidSelectedNotification), object: nil, userInfo: ["emoticon":emoticon])
        
        let paopaoView = WBEmoticonPaopaoView.paopaoView()
        paopaoView.emoticonButton.emoticon = button.emoticon
        let window = UIApplication.shared.windows.last!
        let rect = button.convert(button.bounds, to: window)
        paopaoView.center.x = rect.midX
        paopaoView.frame.origin.y = rect.maxY - paopaoView.frame.height
        window.addSubview(paopaoView)
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) { 
            paopaoView.removeFromSuperview()
        }
    }
    ///MARK: -添加按钮的方法
    private func addChildButtons(){
        for _ in 0..<WBEmoticonCountOfOnePage {
            let button = WBEmoticonButton()
            //按钮点击事件
            button.addTarget(self, action: #selector(emoticonButtonClick(button:)), for: UIControlEvents.touchUpInside)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 30)
            //button.backgroundColor = RandomColor
            self.contentView.addSubview(button)
            self.emoticonButtons.append(button)
        }
        
    }
    
    override func layoutSubviews() {
        let itemW = self.frame.width/7
        let itemH = (self.frame.height - 20)/3
        for (index,button) in emoticonButtons.enumerated() {
            let col = index%7
            let row = index/7
            let x = CGFloat(col)*itemW
            let y = CGFloat(row)*itemH
            button.frame = CGRect(x: x, y: y, width: itemW, height: itemH)
        }
        deleteButton.frame = CGRect(x: self.bounds.width - itemW, y: 2*itemH, width: itemW, height: itemH)
    }
    ///MARK: -懒加载控件
    private lazy var label: UILabel = {
        let label = UILabel(textColor: UIColor.black, fontSize: 35)
        return label
    }()
    private lazy var recentLabel : UILabel = {
        let label = UILabel(textColor: UIColor.lightGray, fontSize: 12)
        label.text = "最近使用的表情"
        return label
    }()
    
    private lazy var deleteButton : UIButton = {
        let button = UIButton()
        button.setImage(#imageLiteral(resourceName: "compose_emotion_delete_highlighted"), for: UIControlState.highlighted)
        button.setImage(#imageLiteral(resourceName: "compose_emotion_delete"), for: UIControlState.normal)
        return button
    }()
    private lazy var paopaoView : WBEmoticonPaopaoView = WBEmoticonPaopaoView.paopaoView()

}
